from flask import Flask, request, render_template
from modules.utils.api import *
from flask_cors import CORS
import json
import yaml
from gevent import pywsgi
from modules.utils.utils import url_to_image, image_to_base64, base64_to_image

app = Flask(__name__)
CORS(app, resources=r'/*')

with open("confs/config.yaml", "r") as f:
    config = yaml.load(f, Loader=yaml.FullLoader)
# print(config)


# 查询算法版本号
@app.route('/version', methods=["GET"])
def version():
    try:
        result_json = json.dumps({"result": 0, "message": "SUCCESS",
                                  "name": "face recognition", "version": config["version"]})
    except Exception as e:
        msg = str(e)
        result_json = json.dumps({"result": -1, "message": msg})
    return result_json


# 人脸信息注册
@app.route('/register', methods=["POST"])
def register():
    image_base64 = json.loads(request.data)["register_image"]
    # image_url = json.loads(request.data)["register_image"]
    # image = url_to_image(image_url)
    image = base64_to_image(image_base64)
    vector_json = face_register(image, score_reg=config["score_reg"])
    return vector_json


# 人脸识别,特征向量和图像比对
@app.route('/match', methods=["POST"])
def match():
    input_data = json.loads(request.data)
    feature_vector = input_data["feature_vector"]
    image_base64 = input_data["real_image"]
    if "thresh" in input_data.keys():
        thresh = input_data["thresh"]
        result = match_identity(feature_vector, thresh=thresh, score_rec=config["score_rec"], image_base64=image_base64)
    else:
        result = match_identity(feature_vector, thresh=0.46, score_rec=config["score_rec"], image_base64=image_base64)
    return result


# 特征向量批量比对，返回过滤后的结果
@app.route('/vector_match', methods=["POST"])
def vector_match():
    input_data = json.loads(request.data)
    ref_id = input_data["ref_id"]
    feature_vector = input_data["feature_vector_witness"]
    candidate_dict = input_data["feature_vector_participant_array"]
    if "threshold_value" in input_data.keys():
        thresh = input_data["threshold_value"]
        result = match_vectors(ref_id, feature_vector, candidate_dict, thresh)
    else:
        result = match_vectors(ref_id, feature_vector, candidate_dict, 0.46)
    return result


# 特征向量批量比对，返回全部欧式距离
@app.route('/vector_match_all', methods=["POST"])
def vector_match_all():
    input_data = json.loads(request.data)
    ref_id = input_data["ref_id"]
    feature_vector = input_data["feature_vector_witness"]
    candidate_dict = input_data["feature_vector_participant_array"]
    result = match_vectors_all(ref_id, feature_vector, candidate_dict)
    return result


if __name__ == '__main__':
    server = pywsgi.WSGIServer((config["host"], config["port"]), app)
    server.serve_forever()
    # app.run(host='0.0.0.0', port=8100, debug=True)
    # app.run(host=config["host"], port=config["port"], debug=True, use_reloader=False)
